package com.jh.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class ChatClient {
    private final String host; //服务器端 IP 地址
    private final int port; //服务器端端口号
    EventLoopGroup group = new NioEventLoopGroup();

    public ChatClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void run() {
        try {
            Bootstrap bootstrap = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ClientInitializer());

            Channel channel = bootstrap.connect(host, port).sync().channel();
            System.out.println("--------" + channel.localAddress().toString().substring(1) + "--------");
            Scanner scanner = new Scanner(System.in);

            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();

                byte[] req = msg.getBytes(StandardCharsets.UTF_8);
                ByteBuf body = Unpooled.wrappedBuffer(req);
//                int v = req.length;

//                byte[] b = new byte[4];
//                b[0] = (byte) ((v >>> 24) & 0xFF);
//                b[1] = (byte) ((v >>> 16) & 0xFF);
//                b[2] = (byte) ((v >>> 8) & 0xFF);
//                b[3] = (byte) ((v >>> 0) & 0xFF);

//                ByteBuf header= Unpooled.buffer(24);
//                header.writeInt(31);

//                ByteBufUtil.

//                Byte
//                ByteBuf buffer = Unpooled.wrappedBuffer(header, body);//Unpooled.copyInt(req.length);

//                buffer.add
//                channel.write(buffer);
//                ByteBuf data = Unpooled.wrappedBuffer(req);
//                channel.write(data);
//                channel.flush();
//
//                ByteBuf b = Unpooled.wrappedBuffer(buffer, data);

//                ByteBufUtil.writeUtf8(buffer, msg);
//                ByteBuf b = Unpooled.compositeBuffer()
//                        .addComponents(true, buffer, data);
//                                .writeBytes(req);

                channel.writeAndFlush(body);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        new ChatClient("127.0.0.1", 8080).run();
    }
}
